package cn.hellochaos.generator.controller;


import cn.hellochaos.generator.entity.dto.ResultCode;
import io.swagger.annotations.*;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import cn.hellochaos.generator.entity.dto.ResultBean;
import cn.hellochaos.generator.service.UserService;
import cn.hellochaos.generator.entity.User;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author fmy
 * @since 2021-07-17
 * @version v1.0
 */
@Api(tags = "用户信息管理，注册登录")
@RestController
@CrossOrigin
@RequestMapping("/fishery/api/v1/user")
@Slf4j
public class UserController {
/*
    注入service
*/
    @Resource
    private UserService userService;


    /**
     * 查询分页数据
     * @param page 页号
     * @param pageSize 页大小
     * @param factor 条件查询值（根据条件后端可以修改）
     * @return
     */

    @RequestMapping(method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @ApiOperation("分页查询所有数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name="page",value="页号",required=false,paramType="query",dataType="Integer"),
            @ApiImplicitParam(name="pageSize",value="页大小",required=false,paramType="query",dataType="Integer"),
            @ApiImplicitParam(name="factor",value="条件查询值（根据条件后端可以修改,默认不传）",required=false,paramType="query",dataType="String")
    })
    public ResultBean<?> listByPage(@RequestParam(name = "page", defaultValue = "1") int page,
                                    @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
                                    @RequestParam(name = "factor", defaultValue = "") String factor) {
        return new ResultBean<>(userService.listUsersByPage(page, pageSize,factor));
    }
    /**
     * 根据id查询
     * @param id
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/{id}",produces = "application/json;charset=UTF-8")
    @ApiOperation("根据id查询user数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="id的值",required=true,paramType="path",dataType="Integer")
    })
    public ResultBean<?> getById(@PathVariable("id") Integer id) {
        //增加健壮性
        User user = userService.getUserById(id);
        if(user==null) {
            return new ResultBean<>(ResultCode.MSG_RESOURCE_NOT_FOUND,ResultCode.RESOURCE_NOT_FOUND);
        }
        return new ResultBean<>(user);
    }

//    /**
//     * 新增
//     * @param user
//     * @return
//     */
//    @RequestMapping(method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
//    @ApiOperation("新增一条user数据")
////    @ApiImplicitParams({
////            @ApiImplicitParam(name="user",value="user的json",required=true,paramType="body")
////    })
//    public ResultBean<?> insert(@RequestBody User user) {
//        return new ResultBean<>(userService.insertUser(user));
//    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id}",produces = "application/json;charset=UTF-8")
    @ApiOperation("删除一条user数据")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name="id",value="user的id",required=true,paramType="path",dataType="Integer")
//    })
    public ResultBean<?> deleteById(@PathVariable("id") Integer id) {
        int deletedId = userService.deleteUserById(id);

        if (deletedId==-1){
            return new ResultBean<>(ResultCode.MSG_RESOURCE_NOT_FOUND,ResultCode.RESOURCE_NOT_FOUND,null);
        }
        return new ResultBean<>(deletedId);
    }
    /**
     * 修改
     * @param user
     * @return
     */
    @RequestMapping(method = RequestMethod.PUT,produces = "application/json;charset=UTF-8")
    @ApiOperation("更新一条user数据")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name="user",value="user的json",required=true,paramType="body")
//    })
//    requestbody不需要用@ApiImplicitParams这种参数注解，只需要@RequestBody注解给参数就行了
    public ResultBean<?> updateById(@RequestBody User user) {
        int updatedId = userService.updateUser(user);

        if (updatedId==-1){
            return new ResultBean<>(ResultCode.MSG_RESOURCE_NOT_FOUND,ResultCode.RESOURCE_NOT_FOUND,null);
        }
        return new ResultBean<>(updatedId);
    }

    /**
     * 注册
     * @param user 参数封装
     * @return ResultBean<?>
     */
    @PostMapping(value = "/register",produces = "application/json;charset=UTF-8")
    @ApiOperation("注册" )
//    @ApiImplicitParams({
//            @ApiImplicitParam(name="user",value="user的json",required=true,paramType="body")
//    })
    @ApiResponses({
            //code重复的情况下，第一个声明的生效。
            @ApiResponse(code = 200,message = "注册成功" ),
            @ApiResponse(code = 20005,message = "用户已存在")
    })
    public ResultBean<?> register(@RequestBody User user){
        return userService.register(user);
    }

    /**
     * 登录
     * @param user 参数封装
     * @return ResultBean<?>
     *     produces 注解指定了返回类型，并且swagger就会标注是这个类型
     */
    @PostMapping(value = "/login",produces = "application/json;charset=UTF-8")
    @ApiOperation("登录")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name="user",value="user的json",required=true,paramType="body")
//    })
    @ApiResponses({
            //code重复的情况下，第一个声明的生效。
            @ApiResponse(code = 200,message = "登录成功" ),
            @ApiResponse(code = 20003,message = "用户名或密码错误")
    })
    public ResultBean<?> login(@RequestBody User user, HttpServletRequest request, HttpServletResponse response){

        /**
         * 测试session
         */
        request.getServletContext().setAttribute("userName",user.getUsername());
        /*
        新增cookie变得有状态
         */
        Cookie cookie = new Cookie("loginUserName",user.getUsername());
        cookie.setPath("/");
        response.addCookie(cookie);

//        HttpSession session=request.getSession();//这就是session的创建
//        session.setAttribute("username",user.getUsername());//给session添加属性属性name： username,属性 value：TOM
//        session.setAttribute("userId",user.getUserId());
        /*
        参数是秒
         */
        //session.setMaxInactiveInterval(60);
        //session.setAttribute("password","tommmm");

        return userService.login(user);
    }
}
